<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="短信类型" prop="type">
        <el-select v-model="queryParams.type" placeholder="请选择短信类型" clearable>
          <el-option
            v-for="dict in dict.type.sms_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="接收者" prop="receiverId">
        <el-autocomplete
          v-model="userSearchKeyword"
          :fetch-suggestions="handleUserSearch"
          placeholder="请输入接收者昵称"
          clearable
          value-key="label"
          @select="handleUserSelect"
          @clear="queryParams.receiverId = null"
          style="width: 100%"
        >
          <template slot-scope="{ item }">
            <div>{{ item.label }}</div>
          </template>
        </el-autocomplete>
      </el-form-item>
      <el-form-item label="短信模板" prop="templateCode">
        <el-select v-model="queryParams.templateCode" placeholder="请选择短信模板代码" clearable>
          <el-option
            v-for="dict in dict.type.sms_template"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="发送状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择发送状态" clearable>
          <el-option
            v-for="dict in dict.type.sms_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker
          v-model="createTimeRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd"
          clearable
          @change="handleCreateTimeChange">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="发送时间" prop="sendTime">
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd"
          clearable
          @change="handleSendTimeChange">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!-- <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['alarm:sms:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['alarm:sms:edit']"
        >修改</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['alarm:sms:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['alarm:sms:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="smsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" fixed/>
      <el-table-column label="序号" align="center" type="index" fixed/>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180px">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="短信类型" align="center" prop="type" width="120px">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sms_type" :value="scope.row.type"/>
        </template>
      </el-table-column>
      <el-table-column label="接收者" align="center" prop="receiverName" width="100px"/>
      <el-table-column label="短信模板" align="center" prop="templateCode" width="120px">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sms_template" :value="scope.row.templateCode"/>
        </template>
      </el-table-column>
      <el-table-column label="发送内容" align="center" prop="content" width="200px" show-overflow-tooltip/>
      <el-table-column label="发送状态" align="center" prop="status" width="80px">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sms_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="发送时间" align="center" prop="sendTime" width="180px">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.sendTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="错误信息" align="center" prop="errorMessage" width="200px" show-overflow-tooltip/>
      <el-table-column label="发送次数" align="center" prop="sendCount" width="80px"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="180px">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['alarm:sms:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['alarm:sms:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改短信发送记录对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="短信类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择短信类型">
            <el-option
              v-for="dict in dict.type.sms_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="接收者" prop="receiverId">
          <el-autocomplete
            v-model="form.receiverName"
            :fetch-suggestions="handleUserSearch"
            placeholder="请输入接收者昵称"
            clearable
            value-key="label"
            @select="(item) => form.receiverId = item.value"
            @clear="form.receiverId = null"
            style="width: 100%"
          >
            <template slot-scope="{ item }">
              <div>{{ item.label }}</div>
            </template>
          </el-autocomplete>
        </el-form-item>
        <el-form-item label="短信模板" prop="templateCode">
          <el-select v-model="form.templateCode" placeholder="请选择短信模板代码">
            <el-option
              v-for="dict in dict.type.sms_template"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="发送内容">
          <el-input
            type="textarea"
            v-model="form.content"
            placeholder="请输入内容"
            :autosize="{ minRows: 2, maxRows: 6 }"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="发送状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择发送状态">
            <el-option
              v-for="dict in dict.type.sms_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="发送时间" prop="sendTime">
          <el-date-picker clearable
            v-model="form.sendTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择发送时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="错误信息" prop="errorMessage">
          <el-input v-model="form.errorMessage" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="发送次数" prop="sendCount">
          <el-input v-model="form.sendCount" placeholder="请输入发送次数" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listSms, getSms, delSms, addSms, updateSms } from "@/api/alarm/sms"
import { listUser } from "@/api/system/user"

export default {
  name: "Sms",
  dicts: ['sms_type', 'sms_status', 'sms_template'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 短信发送记录表格数据
      smsList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        type: null,
        receiverId: null,
        templateCode: null,
        content: null,
        status: null,
        sendTime: null,
        errorMessage: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        createTime: [
          { required: true, message: "创建时间不能为空", trigger: "blur" }
        ],
        type: [
          { required: true, message: "短信类型不能为空", trigger: "change" }
        ],
        receiverId: [
          { required: true, message: "接收者不能为空", trigger: "blur" }
        ],
        templateCode: [
          { required: true, message: "短信模板代码不能为空", trigger: "change" }
        ],
        content: [
          { required: true, message: "发送内容不能为空", trigger: "blur" }
        ],
        status: [
          { required: true, message: "发送状态不能为空", trigger: "change" }
        ],
        sendCount: [
          { required: true, message: "发送次数不能为空", trigger: "blur" }
        ]
      },
      // 用户列表
      userOptions: [],
      // 用户搜索关键字
      userSearchKeyword: '',
      // 用户搜索防抖定时器
      userSearchTimer: null,
      dateRange: [],
      createTimeRange: [],
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询短信发送记录列表 */
    getList() {
      this.loading = true
      listSms(this.queryParams).then(response => {
        this.smsList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        createTime: null,
        type: null,
        receiverId: null,
        templateCode: null,
        content: null,
        status: null,
        sendTime: null,
        errorMessage: null,
        sendCount: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      // this.queryParams.beginSendTime = this.dateRange[0];
      // this.queryParams.endSendTime = this.dateRange[1];
      // this.queryParams.beginCreateTime = this.createTimeRange[0];
      // this.queryParams.endCreateTime = this.createTimeRange[1];
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.createTimeRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加短信发送记录"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getSms(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改短信发送记录"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateSms(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addSms(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除短信发送记录编号为"' + ids + '"的数据项？').then(function() {
        return delSms(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('alarm/sms/export', {
        ...this.queryParams
      }, `sms_${new Date().getTime()}.xlsx`)
    },
    /** 搜索用户 */
    handleUserSearch(query, callback) {
      if (this.userSearchTimer) {
        clearTimeout(this.userSearchTimer)
      }
      return new Promise(resolve => {
        this.userSearchTimer = setTimeout(() => {
          if (query) {
            listUser({ nickName: query }).then(response => {
              
              const suggestions = response.rows.map(user => ({
                value: user.userId,
                label: user.nickName
              }))
              callback(suggestions)
            })
          } else {
            callback([])
          }
        }, 300)
      })
    },
    /** 选择用户 */
    handleUserSelect(item) {
      this.queryParams.receiverId = item.value
    },
    /** 创建时间变化处理 */
    handleCreateTimeChange(val) {
      if (!val) {
        this.queryParams.beginCreateTime = null;
        this.queryParams.endCreateTime = null;
      } else {
        this.queryParams.beginCreateTime = val[0];
        this.queryParams.endCreateTime = val[1];
      }
    },
    /** 发送时间变化处理 */
    handleSendTimeChange(val) {
      if (!val) {
        this.queryParams.beginSendTime = null;
        this.queryParams.endSendTime = null;
      } else {
        this.queryParams.beginSendTime = val[0];
        this.queryParams.endSendTime = val[1];
      }
    },
  }
}
</script>
